package org.example.bombermanclient.network;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.bombermanclient.listener.MessageListener;
import org.example.bombermanclient.model.Message;

public class ClientHandler extends SimpleChannelInboundHandler<Message> {

    private final MessageListener listener;

    public ClientHandler(MessageListener listener) {
        this.listener = listener;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        if (listener != null){
            listener.onConnected();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        if (listener != null) {
            listener.onDisconnected();
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) {
        if (listener != null) {
            listener.onMessageReceived(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
